﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Linq;

namespace ImprovedWebCrawler
{
    public partial class Form1 : Form
    {
        private Crawler crawler;
        private bool isCrawling = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (isCrawling)
            {
                crawler.Stop();
                btnStart.Text = "开始爬取";
                isCrawling = false;
                return;
            }

            string startUrl = txtStartUrl.Text.Trim();
            if (string.IsNullOrEmpty(startUrl))
            {
                MessageBox.Show("请输入起始URL");
                return;
            }

            if (!Uri.TryCreate(startUrl, UriKind.Absolute, out Uri uri))
            {
                MessageBox.Show("URL格式不正确");
                return;
            }

            lstCrawledUrls.Items.Clear();
            lstErrorUrls.Items.Clear();

            crawler = new Crawler(startUrl);
            crawler.PageCrawled += Crawler_PageCrawled;
            crawler.PageError += Crawler_PageError;
            crawler.CrawlCompleted += Crawler_CrawlCompleted;

            btnStart.Text = "停止爬取";
            isCrawling = true;

            new Thread(() => crawler.Start()).Start();
        }

        private void Crawler_CrawlCompleted(object sender, EventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                btnStart.Text = "开始爬取";
                isCrawling = false;
                MessageBox.Show("爬取完成!");
            });
        }

        private void Crawler_PageError(object sender, PageErrorEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                lstErrorUrls.Items.Add($"{e.Url} - {e.ErrorMessage}");
                lstErrorUrls.TopIndex = lstErrorUrls.Items.Count - 1;
            });
        }

        private void Crawler_PageCrawled(object sender, PageCrawledEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                lstCrawledUrls.Items.Add(e.Url);
                lblStatus.Text = $"已爬取: {lstCrawledUrls.Items.Count} 错误: {lstErrorUrls.Items.Count}";
                lstCrawledUrls.TopIndex = lstCrawledUrls.Items.Count - 1;
            });
        }
    }
}